package com.hex.ds.code.detection.pack.conf;

import com.hex.ds.code.detection.pack.constants.AsyncConstants;
import com.hex.ds.code.detection.pack.constants.ScriptScanAsyncConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync()
public class AsyncTaskPoolsConfig {

    private ScriptScanAsyncConstants scriptScanAsyncConstants;

    @Autowired(required = false)
    public AsyncTaskPoolsConfig(ScriptScanAsyncConstants scriptScanAsyncConstants) {
        this.scriptScanAsyncConstants = scriptScanAsyncConstants;
    }

    /**
     * @Method scriptScanAsyncTaskExecutor
     * @Param
     * @Return java.util.concurrent.Executor
     * @Description 脚本文件扫描线程池
     * @Author Wang zhihao
     * @Date 2023/10/9 10:11
     * @Version V1.0
     */
    @Bean(name = "scriptScanAsyncTaskExecutor")
    public Executor scriptScanAsyncTaskExecutor() {
        return initExecutor(scriptScanAsyncConstants, "scriptScanAsyncTaskExecutor-");
    }

    //初始化方法
    private ThreadPoolTaskExecutor initExecutor(AsyncConstants asyncConstants, String prefix) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(asyncConstants.getCorePoolSize());
        threadPoolTaskExecutor.setMaxPoolSize(asyncConstants.getMaxPoolSize());
        threadPoolTaskExecutor.setQueueCapacity(asyncConstants.getQueueCapacity());
        threadPoolTaskExecutor.setKeepAliveSeconds(asyncConstants.getKeepAliveSeconds());
        threadPoolTaskExecutor.setThreadNamePrefix(prefix);
        // 线程池对拒绝任务(无线程可用)的处理策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
